package com.cuitrip.business.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.TextView;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.user.ChooseCityActivity;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.cuitrip.util.MediaFetcher;
import com.lab.app.BaseActivity;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

public class CompleteUserInfoActivity extends BaseActivity {

    @Bind(R.id.user_photo)
    public CircleImageView userPhoto;

    @Bind(R.id.ct_location)
    public TextView userLocation;

    @Bind(R.id.tvDisplay)
    public TextView tvDisplay;

    public static final int REQUEST_COMPLETE_USER = 0x01;

    private boolean mIsUpLoading = false;

    private String mUploadedAvaUrl;

    private OssService ossService = new OssService();

    private ApiProxy apiProxy;
    private ImageFetcherManager mImageFetcherManager = new ImageFetcherManager(this, ImageFetcherManager.Source.SELF_INFO_SELECT);
    private File tempPhotoFile;
    private IProxyCallback callBack = new ApiProxyCallBack() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
            userInfo.setHeadPic(mUploadedAvaUrl);
            RongIM.getInstance().refreshUserInfoCache(new UserInfo(userInfo.getUid(), userInfo.getNick(), Uri.parse(userInfo.getHeadPic())));
            LoginInstance.getInstance().update(CompleteUserInfoActivity.this, userInfo, false);
            finish();
            LogHelper.e("LoginActivity", "jump index");
            Intent intent = new Intent(CompleteUserInfoActivity.this, IndexActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
            return super.onFaild(response);
        }
    };

    private IProxyCallback getOssTokenCallback = new ApiProxyCallBack<OssTokenObject>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(OssTokenObject ossTokenObject, CtApiResponse response) {
            if (ossTokenObject != null) {
                ossService.initClient(ossTokenObject);
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                ossService.asyncPutImage(OssService.getObjectName(userInfo.getUid(), tempPhotoFile), tempPhotoFile.getAbsolutePath(), new OssService.UploadCallback() {
                    @Override
                    public void onFailure(String errorMessage) {
                        mIsUpLoading = false;
                        if (!TextUtils.isEmpty(errorMessage)) {
                            MessageUtils.showToast(errorMessage);
                        }
                    }

                    @Override
                    public void onSuccess(String url) {
                        mUploadedAvaUrl = url;
                        mIsUpLoading = false;
                        setResult(RESULT_OK);

                    }

                    @Override
                    public void onProgress(int progress) {
                        AppLog.d("progress" + progress);
                    }
                });

            }
            return super.onSuccess(ossTokenObject, response);
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_complete_user_info);
        ButterKnife.bind(this);
        CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
        if (ctUserInfo == null) {
            return;
        }
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.MODIFY_USERINFO, callBack)
                .addApiCallBack(ApiManager.GET_MOBILE_OSS_TOKEN, getOssTokenCallback).build();
        //更新界面
        tvDisplay.setText(getString(R.string.other_hello, ctUserInfo.getNick()));
    }

    @OnClick(R.id.ct_location)
    public void chooseLocation() {
        ChooseCityActivity.changUserCity(this);
    }

    @OnClick(R.id.user_photo)
    public void choosePhoto() {
        selectPhoto();
    }

    private void selectPhoto() {
        tempPhotoFile =
                MediaFetcher.getTempImageFilePath(AppCoreRuntime.context);
        if (null == tempPhotoFile) {
            return;
        }
        EasyImage.openChooser(this, "", true);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            skipCompleteInfo();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @OnClick(R.id.tvPass)
    public void skipCompleteInfo() {
        LogHelper.e("LoginActivity", "jump index");
        Intent intent = new Intent(CompleteUserInfoActivity.this, IndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @OnClick(R.id.ct_complete)
    public void completeAction() {
        if (verifyInput()) {
            showLoading();
            Map<String, String> map = new HashMap();
            map.put("headPic", mUploadedAvaUrl);
            UserBusiness.updateProfile(apiProxy, map);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        boolean handleActivity = EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                boolean pickImageSuccess = mImageFetcherManager.cropImage(imageFile, tempPhotoFile, null);
                if (!pickImageSuccess) {
                    MessageUtils.showToast(R.string.feedback_data_err);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });

        if (ImageFetcherManager.REQUEST_CODE_CROP_IMAGE == requestCode) {
            if (resultCode == RESULT_OK) {
                Bitmap bp = null;
                if (tempPhotoFile != null) {
                    bp = GetImageHelper.getResizedBitmap(this, Uri.fromFile(tempPhotoFile));
                }
                if (bp == null) {
                    MessageUtils.showToast(getString(R.string.feedback_upload_fail));
                } else {
                    userPhoto.setImageBitmap(bp);
                    updateImage();
                }
            }
        }

        if (requestCode == ChooseCityActivity.REQUEST_CODE_CHANGE_USER_CITY) {
            if (resultCode == RESULT_OK) {
                if (data.hasExtra(ChooseCityActivity.CITY_KEY)) {
                    userLocation.setText(data.getStringExtra(ChooseCityActivity.CITY_KEY));
                }
            }
        }
    }

    protected void updateImage() {
        mIsUpLoading = true;
        showLoading();
        CommonBusiness.getMobileOssToken(apiProxy);
    }

    private boolean verifyInput() {
        if (TextUtils.isEmpty(mUploadedAvaUrl)) {
            Utils.shakeView(userPhoto);
            return false;
        } else if (mIsUpLoading) {
            ToastUtil.toast("正在上传图片");
            return false;
        } else if (TextUtils.isEmpty(userLocation.getText().toString())) {
            Utils.shakeView(userLocation);
            return false;
        } else {
            return true;
        }
    }
}

